//
//  CYUserCarPublishTableVC.m
//  CreditAddressBook
//
//  Created by LE on 15/12/17.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYUserCarPublishTableVC.h"
#import "LEBarButtonItem.h"
#import "CYSelectCarVC.h"
#import "CYCarInfo.h"
#import "UIImageView+WebCache.h"
#import "LEImagePicker.h"
#import "CYDiscoveryHttpTool.h"
#import "MBProgressHUD+MJ.h"
#import "LEMDLib.h"
#import "UIInfomationView.h"
#import "CYCarRental.h"
#import "CYLoginHttpTool.h"
#import "CYCompanyUserTool.h"
#import "CYCarCompanyAccount.h"
#import "CYCarUserAccount.h"
#import "CYCreditTool.h"
#import "MDSlider.h"
#import "TOWebViewController+LE.h"
#import "CYUserCarFindWebVC.h"
#import "LEImagePickerTool.h"

@interface CYUserCarPublishTableVC ()<UIWebViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *carImageView;
@property (weak, nonatomic) IBOutlet UITextField *name;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *idCardTF;
@property (weak, nonatomic) IBOutlet UILabel *rewardLabel;
@property (weak, nonatomic) IBOutlet UITextField *priceTF;
@property (weak, nonatomic) IBOutlet UITextField *depositTF;
@property (weak, nonatomic) IBOutlet UITextField *distanceTF;
@property (weak, nonatomic) IBOutlet UITextField *commentTF;
@property (weak, nonatomic) IBOutlet UIButton *rentDateBtn;
@property (weak, nonatomic) IBOutlet MDSlider *silderView;
@property (weak, nonatomic) IBOutlet UIButton *ykjBtn;

@property(nonatomic, strong) CYCarInfo *carInfo;
@property(nonatomic, strong) LEImagePicker *imagePicker;

@property(nonatomic, strong) CYCarRental *model;
@property(nonatomic, assign) NSInteger carReward;
@property(nonatomic, strong) NSDate *carRentalDate;
@property(nonatomic, assign) NSInteger rentType;

@property(nonatomic, copy) CYCompletionBlock block;

@property(nonatomic, assign) CGFloat balance;//风险金余额
@end

@implementation CYUserCarPublishTableVC

- (CYCarRental *)model {
    if (!_model) {
        _model = [CYCarRental new];
    }
    return _model;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self submitBtn];
    [self loadData];
}

- (void)submitBtn {
    LEBarButtonItem *item = [[LEBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Checked Checkbox 2-50"] andSelImage:[UIImage imageNamed:@"Checked Checkbox 2-50_h"] target:self action:@selector(submit)];
    self.navigationItem.rightBarButtonItem = item;
    
    self.imagePicker = [[LEImagePicker alloc] init];
    //设置初始化租车日期
    self.carRentalDate = [NSDate date];
    [self.rentDateBtn setTitle:[CYCreditTool timeWithDate:[NSDate date] formatter:@"yyyy-MM-dd"] forState:UIControlStateNormal];
    
    [self.ykjBtn setBackgroundImage:[UIImage resizedImageWithName:@"select_bg" left:.1 top:.1] forState:UIControlStateNormal];
}

- (void)loadData {
    self.silderView.enabled = NO;
    NSDictionary *param = nil;
    if (self.userType == CYUserTypePerson) {
        CYUser *user = [CYLoginHttpTool userData].user;
        if (user) {
            param = @{@"userId": user.userId, @"token": user.token};
            [CYDiscoveryHttpTool getUserCarRewardWithParam:param success:^(NSNumber *account, NSNumber *riskAccount) {
                CGFloat step = 5000;
                if (account.doubleValue < step) {
                    [MBProgressHUD showError:@"账号余额不足，请充值后再操作"];
                } else {
                    self.balance = account.integerValue;
                    //silder
                    self.silderView.enabled = YES;
                    self.silderView.step = step;
                    self.silderView.minimumValue = 0;
                    self.silderView.maximumValue = account.integerValue;
                }
            } failure:^(NSString *message, BOOL isLogin) {
                if (!isLogin) {
                    [CYLoginHttpTool logoutWithController:self];
                    [self.navigationController popToRootViewControllerAnimated:NO];
                }
                [MBProgressHUD showError:message];
            }];
        } else {
            [MBProgressHUD showError:@"请登陆后再操作"];
            return;
        }
    } else if (self.userType == CYUserTypeCompany) {
        CYCompanyUserModel *user = [CYCompanyUserTool companyUser];
        if (user) {
            param = @{@"userId": user.carCompanyUserId, @"companyId": user.companyId, @"token": user.token};
            [CYDiscoveryHttpTool getCompanyCarRewardWithParam:param success:^(NSNumber *account, NSNumber *riskAccount) {
                CGFloat step = 5000;
                if (account.doubleValue < step) {
                    [MBProgressHUD showError:@"账号余额不足，请充值后再操作"];
                } else {
                    self.balance = account.integerValue;
                    //silder
                    self.silderView.enabled = YES;
                    self.silderView.step = step;
                    self.silderView.minimumValue = 0;
                    self.silderView.maximumValue = account.integerValue;
                }
            } failure:^(NSString *message, BOOL isLogin) {
                if (!isLogin) {
                    [CYCompanyUserTool logoutWithController:self];
                    [self.navigationController popToRootViewControllerAnimated:NO];
                }
                [MBProgressHUD showError:message];
            }];
        } else {
            [MBProgressHUD showError:@"请登陆后再操作"];
            return;
        }
    }
}

- (void)submit {
    [self.view endEditing:YES];
    if ([self setupCarRental]) {
        CYWeakObject(weakself, self);
        [CYDiscoveryHttpTool addCarRentalWithParam:self.model success:^(NSString *message) {
            [MBProgressHUD showSuccess:message];
            if (weakself.block) {
                weakself.block();
                weakself.block = nil;
            }
            //发出通知刷新租车列表
            [CYNotificationCenter postNotificationName:nCYReloadDataOfCarLeaseAndDrop object:nil];
            [weakself.navigationController popViewControllerAnimated:YES];
        } failure:^(NSString *message, NSError *error) {
            if (message) {
//                [MBProgressHUD showError:message];
                [LEMDLib showLongToaskWithMessgage:message];
            }
        }];
    }
}

- (BOOL)setupCarRental {
    CYCarRental *model = self.model;
    if (self.userType == CYUserTypePerson) {
        CYUser *user = [CYLoginHttpTool userData].user;
        if (user) {
            model.userId = user.userId;
        } else {
            [MBProgressHUD showError:@"请登陆后再操作"];
            return NO;
        }
        
    } else if (self.userType == CYUserTypeCompany) {
        CYCompanyUserModel *user = [CYCompanyUserTool companyUser];
        if (user) {
            model.companyId = user.companyId;
            model.userId = user.carCompanyUserId;
        } else {
            [MBProgressHUD showError:@"请登陆后再操作"];
            return NO;
        }
    } else {
        [MBProgressHUD showError:@"请登陆后再操作"];
        return NO;
    }
    model.type = @(self.userType);
    if (self.carInfo.carInfoId && !self.carInfo.carInfoId.isEmpty) {
        model.carInfoId = self.carInfo.carInfoId;
    } else {
        [MBProgressHUD showError:@"请选择发布车辆"];
        return NO;
    }
    if (self.name.text && !self.name.text.isEmpty) {
        model.name = self.name.text;
    } else {
        [MBProgressHUD showError:@"请输入姓名"];
        return NO;
    }
    if (self.phoneTF.text && !self.phoneTF.text.isEmpty) {
        model.phone = self.phoneTF.text;
    } else {
        [MBProgressHUD showError:@"请输入手机号码"];
        return NO;
    }
    if (self.idCardTF.text && !self.idCardTF.text.isEmpty) {
        model.certificateNo = self.idCardTF.text;
    } else {
        [MBProgressHUD showError:@"请输入身份证号"];
        return NO;
    }
    if (self.carReward != 0) {
        model.carReward = @(self.carReward);
    } else {
        [MBProgressHUD showError:@"风险赏金不能为零"];
        return NO;
    }
    if (self.carRentalDate) {
        NSString *dateStr = [CYCreditTool timeWithDate:self.carRentalDate formatter:@"yyyy-MM-dd HH:mm:ss"];
        model.carRentalDate = dateStr;
    } else {
        [MBProgressHUD showError:@"请选择租车日期"];
        return NO;
    }
    if (self.priceTF.text && !self.priceTF.text.isEmpty) {
        model.rent = @(self.priceTF.text.integerValue);
        model.rentType = @(self.rentType);
    } else {
        [MBProgressHUD showError:@"请输入押金或者一口价"];
        return NO;
    }
    if (self.carInfo.carInfoId && !self.carInfo.carInfoId.isEmpty) {
    } else {
        [MBProgressHUD showError:@"请选择发布车辆"];
        return NO;
    }
    if (self.depositTF.text && !self.depositTF.text.isEmpty) {
        model.cashPledge = @(self.depositTF.text.integerValue);
    } else {
        [MBProgressHUD showError:@"请输入押金"];
        return NO;
    }
    if (self.distanceTF.text && !self.distanceTF.text.isEmpty) {
        model.carMileage = @(self.distanceTF.text.integerValue);
    }
    if (self.commentTF.text && !self.commentTF.text.isEmpty) {
        model.remark = self.commentTF.text;
    }
    if (!model.certificateNoZAddress || model.certificateNoZAddress.isEmpty) {
        [MBProgressHUD showError:@"请上传身份证正面照"];
        return NO;
    }
    if (!model.certificateNoFAddress || model.certificateNoFAddress.isEmpty) {
        [MBProgressHUD showError:@"请上传身份证反面照"];
        return NO;
    }
    if (self.carInfo.plateNumber) {
        model.plateNumber = self.carInfo.plateNumber;
    } else {
        [MBProgressHUD showError:@"车辆信息错误"];
    }
    return YES;
}

- (IBAction)selectCar:(UIButton *)sender {
    [self.view endEditing:YES];
    CYSelectCarVC *car = [[CYSelectCarVC alloc] init];
    car.userType = self.userType;
    CYWeakObject(weakself, self);
    [car selectedCarInfo:^(CYCarInfo *carInfo) {
        weakself.carInfo = carInfo;
        if (carInfo.photo && !carInfo.photo.isEmpty) {
            [weakself.carImageView sd_setImageWithURL:CYURLWithUserService(carInfo.photo) placeholderImage:[UIImage imageNamed:@""]];
        }
    }];
    [self.navigationController pushViewController:car animated:YES];
}
- (IBAction)uploadIdCardZBtn:(LEProgressButton *)sender {
    [self.view.window endEditing:YES];
    CYWeakObject(weakself, self);
    [LEImagePickerTool selectImageWithController:self edit:YES completion:^(UIImage *image) {
        [CYDiscoveryHttpTool uploadUserImage:image button:sender success:^(NSString *imagePath) {
            weakself.model.certificateNoZAddress = imagePath;
        } failure:^(NSString *message, NSError *error) {
            if (message) {
                [MBProgressHUD showError:message];
            }
        }];
    }];
//    [self.imagePicker showInController:self handler:^(UIImage *image) {
//        [CYDiscoveryHttpTool uploadUserImage:image button:sender success:^(NSString *imagePath) {
//            weakself.model.certificateNoZAddress = imagePath;
//        } failure:^(NSString *message, NSError *error) {
//            if (message) {
//                [MBProgressHUD showError:message];
//            }
//        }];
//    }];
}
- (IBAction)uploadIdCardFBtn:(LEProgressButton *)sender {
    [self.view.window endEditing:YES];
    CYWeakObject(weakself, self);
    [LEImagePickerTool selectImageWithController:self edit:YES completion:^(UIImage *image) {
        [CYDiscoveryHttpTool uploadUserImage:image button:sender success:^(NSString *imagePath) {
            weakself.model.certificateNoFAddress = imagePath;
        } failure:^(NSString *message, NSError *error) {
            if (message) {
                [MBProgressHUD showError:message];
            }
        }];
    }];
//    [self.imagePicker showInController:self handler:^(UIImage *image) {
//        [CYDiscoveryHttpTool uploadUserImage:image button:sender success:^(NSString *imagePath) {
//            weakself.model.certificateNoFAddress = imagePath;
//        } failure:^(NSString *message, NSError *error) {
//            if (message) {
//                [MBProgressHUD showError:message];
//            }
//        }];
//    }];
}
- (IBAction)rewardSlider:(UISlider *)sender {
    [self.view endEditing:YES];
    NSInteger value = self.balance*sender.value;
    self.carReward = value;
    self.rewardLabel.text = CYStringFormat(@"￥%ld", (long)value);
}
- (IBAction)datePickerBtn:(UIButton *)sender {
    [self.view endEditing:YES];
    [LEMDLib showDatePickerWithDateFormatter:@"yyyy-MM-dd" completion:^(NSString *dateStr, NSDate *date) {
        [sender setTitle:dateStr forState:UIControlStateNormal];
        self.carRentalDate = date;
    }];
}
- (IBAction)statusBtn:(UIButton *)sender {
    [self.view endEditing:YES];
    [UIInfomationView showActionSheetInView:self.view WithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"一口价", @"日租金"] clickAtIndex:^(NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            [sender setTitle:@"一口价" forState:UIControlStateNormal];
            self.priceTF.placeholder = @"该车租赁的一口价";
            self.rentType = 1;
        } else if (buttonIndex == 2) {
            [sender setTitle:@"日租金" forState:UIControlStateNormal];
            self.priceTF.placeholder = @"该车的日租金";
            self.rentType = 0;
        }
    }];
}
- (IBAction)sliderView:(id)sender {
    [self.view endEditing:YES];
//    NSInteger value = self.balance*(self.silderView.value*0.01);
    self.carReward = self.silderView.value;
    self.rewardLabel.text = CYStringFormat(@"￥%ld", (long)self.silderView.value);
}
/**
 *  查询
 *
 */
- (IBAction)creditQueryBtn:(UIButton *)sender {
    [self.view endEditing:YES];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (self.phoneTF && !self.phoneTF.text.isEmpty) {
        param[@"phone"] = self.phoneTF.text;
    } else {
//        [MBProgressHUD showError:@"请输入租车人电话号码"];
        param[@"phone"] = @"123";
//        return;
    }
    if (self.name && !self.name.text.isEmpty) {
        param[@"name"] = self.name.text;
    } else {
//        [MBProgressHUD showError:@"请输入租车人姓名"];
        param[@"name"] = @"123";
//        return;
    }
    if (self.idCardTF.text && !self.idCardTF.text.isEmpty) {
        param[@"condition"] = self.idCardTF.text;
//        param = @{@"condition": self.idCardTF.text, @"phone": self.phoneTF.text, @"name": self.name.text};
    } else if (self.carInfo.plateNumber && !self.carInfo.plateNumber.isEmpty) {
        param[@"condition"] = self.carInfo.plateNumber;
//        param = @{@"condition": self.carInfo.plateNumber, @"phone": self.phoneTF.text, @"name": self.name.text};
    } else {
        param = nil;
    }
    if (param) {
//        NSString *url = [CYURL shared].creditQuery;
//        TOWebViewController *web = [TOWebViewController createWebViewControllerWithURL:url param:param];
//        [self.navigationController pushViewController:web animated:YES];
        //@{@"condition": @"530302199302091213"}
        
        CYUserCarFindWebVC *webvc = [[CYUserCarFindWebVC alloc] init];
        webvc.param = param;
        [self.navigationController pushViewController:webvc animated:YES];
    } else {
       [MBProgressHUD showError:@"请输入身份证号"];
    }
}
#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return .1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}


#pragma mark - 
- (void)completion:(CYCompletionBlock)completion {
    self.block = [completion copy];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

- (void)dealloc {
    CYLog(@"车辆发布销毁");
}
@end
